﻿@using Partner.Surround.Authorization
@using Partner.Surround.Web.Startup
@{
    ViewBag.CurrentPageName = PageNames.OrganizationUnits;
}
@section styles{
    <link href="~/css/treetable.css" rel="stylesheet" />
    <link href="~/lib/layui-extend-modules/ztree/metroStyle/metroStyle.css" rel="stylesheet" />
}

<!--机构列表-->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-btn-container">
                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Delete))
                {
                    <button class="layui-btn layui-btn-organizationUnit" data-type="batchdel">删除</button>
                }
                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Create))
                {
                    <button class="layui-btn layui-btn-organizationUnit" data-type="add">添加</button>
                }
            </div>
            <div class="layui-row">
                <div class="layui-col-md2 layui-col-xs12">
                    <ul id="tree" class="ztree" style="padding: 0px; border: 1px solid #ddd; overflow: auto;"></ul>
                </div>
                <div class="layui-col-md10 layui-col-xs12">
                    <table class="layui-table"
                           lay-data="{height: 'full-100', page:true, id:'organizationUnitList'}"
                           lay-filter="organizationUnitList">
                        <thead>
                            <tr>
                                <th lay-data="{checkbox:true, fixed: true,width:40}"></th>
                                <th lay-data="{field:'displayName', sort: true}">组织名称</th>
                                <th lay-data="{field:'memberCount'}">成员数量</th>
                                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Update) ||
                             await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Delete))
                                {
                                    <th lay-data="{fixed:'right', align:'center', toolbar: '#organizationUnitBarList'}"></th>
                                }
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!--列表按钮-->
<script type="text/html" id="organizationUnitBarList">
    <div class="layui-table-cell laytable-cell-1-0-9">
        @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Update))
        {
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
        }
        @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_OrganizationUnits_Delete))
        {
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
        }
    </div>
</script>

@section scripts{
    <script type="text/javascript">
        layui.config({
            base: '/lib/layui-extend-modules/' //静态资源所在路径
        }).extend({
            ztree: 'ztree/ztree'
        }).use(['jquery', 'ztree', 'table'], function () {
            var $ = layui.$,
                table = layui.table,
                ztree = layui.ztree;

            //主列表加载，可反复调用进行刷新
            var config = {};  //table的参数，如搜索key，点击tree的id
            var loadOrganizationUnitList = function (options) {
                if (options != undefined) {
                    $.extend(config, options);
                }
                table.reload('organizationUnitList', {
                    url: "@Url.Action("GetPagedOrganizationUnit", "OrganizationUnits")",
                    where: config,
                    parseData: function (res) {
                        return {
                            "code": res.result.code, //解析接口状态
                            "msg": res.result.msg, //解析提示文本
                            "count": res.result.count, //解析数据长度
                            "data": res.result.data //解析数据列表
                        };
                    },
                    response: {
                        statusCode: 200 //规定成功的状态码，默认：0
                    }
                });
            };

            //左边树状机构列表
            var zTree = function () {
                var zTreeObj;
                var setting = {
                    view: { selectedMulti: false },
                    data: {
                        key: {
                            name: 'displayName',
                            title: 'displayName'
                        },
                        simpleData: {
                            enable: true,
                            idKey: 'id',
                            pIdKey: 'parentId',
                            rootPId: 'null'
                        }
                    },
                    edit: {
                        drag: {
                            isCopy: false,
                            isMove: true
                        },
                        showRemoveBtn: false,
                        showRenameBtn: false,
                        enable: true//设置 zTree 是否处于编辑状态
                    },
                    callback: {
                        onClick: function (event, treeId, treeNode) {
                            var organizationUnitId = treeNode.id != null ? treeNode.id : "";
                            loadOrganizationUnitList({ id: organizationUnitId });
                        },
                        beforeDrop: function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
                            var currNodeId = treeNodes[0].id;
                            var currNodeParentId = treeNodes[0].parentId;
                            var targetNodeId = targetNode.id;
                            if (currNodeParentId == targetNodeId) {
                                parent.layer.alert("节点所在位置没有变化");
                                return false;
                            }
                            if (currNodeParentId == "" || targetNodeId == "") {
                                parent.layer.alert("只能移动子级节点。");
                                return false;
                            }

                            abp.ajax({
                                url: "@Url.Action("MoveOrganizationUnit", "OrganizationUnits")",
                                data: JSON.stringify({ "id": currNodeId, "newParentId": targetNodeId })
                            }).done(function (data) {
                                if (data.code == 200) {
                                    var currNode = zTreeObj.getSelectedNodes();
                                    currNode = data.organizationUnit;
                                    zTreeObj.updateNode(currNode);

                                    var organizationUnitId = targetNodeId != null ? targetNodeId : "";
                                    loadOrganizationUnitList({ id: targetNodeId });
                                }
                            }).fail(function (jqXHR) {
                                parent.layer.msg(jqXHR.message, { icon: 5 });
                            });
                        }
                    }
                };
                var load = function () {
                    abp.ajax({
                        type:"Get",
                        url: "@Url.Action("GetOrganizationUnitList", "OrganizationUnits")"
                    }).done(function (result) {
                        var treeNodes = result.data;
                        var rootNode = { displayName: "根节点", id: null, parentId: "" };
                        treeNodes.push(rootNode);

                        zTreeObj = $.fn.zTree.init($("#tree"), setting);
                        zTreeObj.addNodes(null, treeNodes);
                        zTreeObj.expandAll(true);

                        loadOrganizationUnitList({ id: "" });
                    }).fail(function (jqXHR) {
                        parent.layer.msg(jqXHR.message, { icon: 5 });
                    });
                };
                load();
                return {
                    reload: load
                };
            }();
            $("#tree").height($("div.layui-row").height() - 2);

            //删除组织机构
            function deleteOrganizationUnit(data) {
                parent.layer.confirm('确定删除吗?', function (index) {
                    abp.ajax({
                        url: "@Url.Action("DeleteOrganizationUnit", "OrganizationUnits")",
                        data: JSON.stringify(data)
                    }).done(function (data) {
                        if (data.code == 200) {
                            abp.notify.success(data.msg);
                            zTree.reload();//刷新树
                        }
                    }).fail(function (jqXHR) {
                        parent.layer.msg(jqXHR.message, { icon: 5 });
                    }).always(function () {
                        parent.layer.close(index);
                    });
                });
            }

            //创建或更新组织机构
            function createOrUpdateOrganizationUnit(organizationUnitData) {
                parent.layer.open({
                    type: 2,
                    title: organizationUnitData.title,
                    content: organizationUnitData.content,
                    area: ['450px', '249px'],
                    btn: ['确定', '取消'],
                    yes: function(index, layero){
                        parent.window['layui-layer-iframe'+ index].layui.submitForm();
                    }
                });
            }

            //创建或更新完毕回调
            layui.callback = function (data) {
                parent.layer.close(data.index); //关闭弹层
                abp.notify.success(data.msg);
                zTree.reload();//刷新树
            }

            //监听工具条
            table.on('tool(organizationUnitList)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {   //删除
                    deleteOrganizationUnit([{ "id": data.id }]);
                } else if (obj.event === 'edit') {  //编辑
                    var organizationUnitData = {
                        title: '编辑部门信息',
                        content: "@Url.Action("CreateOrUpdateOrganizationUnit", "OrganizationUnits")"+"?id=" + data.id,
                    };
                    createOrUpdateOrganizationUnit(organizationUnitData);
                }
            });

            //监听页面主按钮操作
            var active = {
                add: function () {//添加
                    var treeObj = $.fn.zTree.getZTreeObj("tree");
                    var currSelectedNode = treeObj.getSelectedNodes();
                    if (currSelectedNode == undefined || currSelectedNode.length == 0) {
                        parent.layer.msg("请先选择部门");
                        return;
                    }

                    var organizationUnitData = {
                        title: '添加新部门',
                        content: "@Url.Action("CreateOrUpdateOrganizationUnit", "OrganizationUnits")"+"?parentId=" + (currSelectedNode[0].id != null ? currSelectedNode[0].id : ""),
                    };
                    createOrUpdateOrganizationUnit(organizationUnitData);
                },
                batchdel: function () { //批量删除
                    var checkStatus = table.checkStatus('organizationUnitList'),
                        checkData = checkStatus.data; //得到选中的数据

                    if (checkData.length === 0) {
                        return parent.layer.msg('请选择数据');
                    }

                    var ids = checkData.map(function (d) { return { "id": d.id }; });
                    deleteOrganizationUnit(ids);
                }
            };

            //点击事件转发器
            $('.layui-btn.layui-btn-organizationUnit').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
        });
    </script>
}
